import { apiConfig } from '../../shared/services/api-config'
import type { ApiResponse } from '../../../types/api' 

// 章节内容接口
export interface ChapterContent {
  id?: number
  bookId: number
  chapterNumber: number
  wordNum?: number
  chapterTitle: string
  chapterOutline?: string
  content?: string
  version?: number
  status?: number
  taskId?: string
  errorMessage?: string
  createTime?: string
  updateTime?: string
}

// 生成章节细纲请求接口
export interface ChapterOutlineGenerationRequest {
  bookId: number
  startChapterNumber?: number
  chapterCount: number
  modelId: number
  promptTemplateId?: number
}

// 章节内容API
export const chapterContentApi = {
  // 根据书籍ID获取所有章节
  async getChaptersByBookId(bookId: number): Promise<ApiResponse<ChapterContent[]>> {
    const response = await apiConfig.getAxiosInstance().get(`/chapter/book/${bookId}`)
    return response.data
  },
  
  // 根据书籍ID和章节号获取章节
  async getChapterByBookIdAndNumber(bookId: number, chapterNumber: number): Promise<ApiResponse<ChapterContent>> {
    const response = await apiConfig.getAxiosInstance().get(`/chapter/book/${bookId}/chapter/${chapterNumber}`)
    return response.data
  },
  
  // 根据ID获取章节
  async getChapterById(id: number): Promise<ApiResponse<ChapterContent>> {
    const response = await apiConfig.getAxiosInstance().get(`/chapter/${id}`)
    return response.data
  },
  
  // 创建或更新章节
  async saveOrUpdateChapter(chapter: ChapterContent): Promise<ApiResponse<ChapterContent>> {
    const response = await apiConfig.getAxiosInstance().post('/chapter', chapter)
    return response.data
  },
  
  // 删除章节
  async deleteChapter(id: number): Promise<ApiResponse<string>> {
    const response = await apiConfig.getAxiosInstance().delete(`/chapter/${id}`)
    return response.data
  },
  
  // 生成章节细纲
  async generateChapterOutlines(request: ChapterOutlineGenerationRequest): Promise<ApiResponse<string>> {
    const response = await apiConfig.getAxiosInstance().post('/chapter/outline/generate', request)
    return response.data
  },
  
  // 获取章节细纲任务状态
  async getChapterOutlineTaskStatus(taskId: string): Promise<ApiResponse<any>> {
    const response = await apiConfig.getAxiosInstance().get(`/chapter/outline/task/${taskId}`)
    return response.data
  },
  
  // 获取章节细纲任务结果
  async getChapterOutlineTaskResult(taskId: string): Promise<ApiResponse<any>> {
    const response = await apiConfig.getAxiosInstance().get(`/chapter/outline/task/${taskId}/result`)
    return response.data
  },
  
  // 取消章节细纲任务
  async cancelChapterOutlineTask(taskId: string): Promise<ApiResponse<string>> {
    const response = await apiConfig.getAxiosInstance().delete(`/chapter/outline/task/${taskId}`)
    return response.data
  },
  
  // 根据书籍ID分页查询章节细纲
  async getChapterOutlinesByBookId(bookId: number, pageNum: number = 1, pageSize: number = 10): Promise<ApiResponse<any>> {
    const response = await apiConfig.getAxiosInstance().get(`/chapter/outline/book/${bookId}`, {
      params: { pageNum, pageSize }
    })
    return response.data
  },
  
  // 生成章节正文流式接口
  async generateChapterContentStream(request: {
    bookId: number;
    chapterNumber: number;
    modelId: number;
    systemPromptTemplateId: number;
  }, callbacks: {
    onMessage: (data: string) => void;
    onError: (error: Error) => void;
    onComplete: () => void;
  }): Promise<void> {
    try {
      // 构建请求头
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
        'Accept': 'text/plain;charset=UTF-8'
      }
      
      // 添加Authorization头
      const token = await import('../../shared/services/api-config').then(m => m.ApiConfig.getToken());
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }
      
      // 使用fetch API调用流式接口
      const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8080'}/chapter/content/generateStream`, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(request)
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      // 获取流式响应
      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      
      // 累积内容
      let accumulatedContent = '';
      
      if (reader) {
        let done = false;
        while (!done) {
          const { value, done: readerDone } = await reader.read();
          done = readerDone;
          
          if (value) {
            const chunk = decoder.decode(value, { stream: true });
            
            // 累积内容
            accumulatedContent += chunk;
            
            // 触发消息回调，发送累积的完整内容
            callbacks.onMessage(accumulatedContent);
          }
        }
      }
      
      // 流结束，触发完成回调
      callbacks.onComplete();
    } catch (error) {
      console.error('生成章节正文流式响应失败:', error);
      callbacks.onError(error as Error);
      throw error;
    }
  },
  
  // 生成章节正文异步任务接口
  async generateChapterContentAsync(request: {
    bookId: number;
    chapterId?: number;
    chapterNumber?: number;
    outline: string;
    model: string;
    prompt?: string;
  }): Promise<ApiResponse<{ taskId: string }>> {
    const response = await apiConfig.getAxiosInstance().post('/chapter/content/generateAsync', request)
    return response.data
  },
  
  // 获取章节正文任务状态
  async getChapterContentTaskStatus(taskId: string): Promise<ApiResponse<any>> {
    const response = await apiConfig.getAxiosInstance().get(`/chapter/content/task/${taskId}`)
    return response.data
  },
  
  // 获取章节正文任务结果
  async getChapterContentTaskResult(taskId: string): Promise<ApiResponse<any>> {
    const response = await apiConfig.getAxiosInstance().get(`/chapter/content/task/${taskId}/result`)
    return response.data
  },
  
  // 取消章节正文任务
  async cancelChapterContentTask(taskId: string): Promise<ApiResponse<string>> {
    const response = await apiConfig.getAxiosInstance().delete(`/chapter/content/task/${taskId}`)
    return response.data
  }
}